package com.xiaoshuidi.cloud.module.rooms.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.annotations.VisibleForTesting;
import com.xiaoshuidi.cloud.framework.common.exception.ServiceException;
import com.xiaoshuidi.cloud.framework.common.exception.enums.GlobalErrorCodeConstants;
import com.xiaoshuidi.cloud.framework.common.pojo.CommonResult;
import com.xiaoshuidi.cloud.framework.common.util.json.JsonUtils;
import com.xiaoshuidi.cloud.framework.oss.core.OosFileService;
import com.xiaoshuidi.cloud.framework.security.core.util.SecurityFrameworkUtils;
import com.xiaoshuidi.cloud.module.rooms.controller.admin.roomequipment.vo.*;
import com.xiaoshuidi.cloud.module.rooms.convert.roomequipment.RoomEquipmentConvert;
import com.xiaoshuidi.cloud.module.rooms.enums.EquipmentOwn;
import com.xiaoshuidi.cloud.module.rooms.enums.EquipmentPositionType;
import com.xiaoshuidi.cloud.module.rooms.enums.EquipmentStatus;
import com.xiaoshuidi.cloud.module.rooms.enums.RoomTypeEnum;
import com.xiaoshuidi.cloud.module.rooms.framework.utils.CodeUtil;
import com.xiaoshuidi.cloud.module.rooms.mapper.RoomEquipmentMapper;
import com.xiaoshuidi.cloud.module.rooms.mq.listener.PartLeaseEquipmentListener;
import com.xiaoshuidi.cloud.module.rooms.mq.listener.WholeLeaseEquipmentListener;
import com.xiaoshuidi.cloud.module.rooms.pojo.*;
import com.xiaoshuidi.cloud.module.rooms.repository.ApartmentRepository;
import com.xiaoshuidi.cloud.module.rooms.repository.EquipmentSupplierRepository;
import com.xiaoshuidi.cloud.module.rooms.repository.RoomHouseRepository;
import com.xiaoshuidi.cloud.module.rooms.repository.irepository.IEquipmentCategoryRepository;
import com.xiaoshuidi.cloud.module.rooms.repository.irepository.IEquipmentSupplierRepository;
import com.xiaoshuidi.cloud.module.rooms.repository.irepository.IRoomEquipmentRepository;
import com.xiaoshuidi.cloud.module.rooms.service.RoomEquipmentService;
import com.xiaoshuidi.cloud.module.rooms.vo.RoomEquipmentVO;
import com.xiaoshuidi.cloud.module.system.api.user.AdminUserApi;
import com.xiaoshuidi.cloud.module.system.api.user.dto.AdminUserRespDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @Author Feng
 * @date 2023/4/27
 */
@Slf4j
@Service
@Validated
@RequiredArgsConstructor
public class RoomEquipmentServiceImpl extends ServiceImpl<RoomEquipmentMapper, RoomEquipment> implements RoomEquipmentService {

    @Resource
    private IEquipmentCategoryRepository equipmentCategoryRepository;
    @Resource
    private IRoomEquipmentRepository roomEquipmentRepository;
    @Resource
    private IEquipmentSupplierRepository equipmentSupplierRepository;
    @Resource
    private RoomHouseRepository roomHouseRepository;
    @Resource
    private CodeUtil codeUtil;
    @Resource
    private ApartmentRepository apartmentRepository;

    @Resource
    private EquipmentSupplierRepository supplierRepository;

    private final PlatformTransactionManager transactionManager;

    private final TransactionDefinition transactionDefinition;
    private final StringRedisTemplate stringRedisTemplate;

    private final OosFileService oosFileService;

    private final AdminUserApi adminUserApi;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long create(RoomEquipmentCreateReq req) {
        //校验图片，最大不能超过五张，批量上传不能上传所以不校验此项
        validatePic(req.getPic());
        // 校验资产类别是否存在
        validateCategoryId(req.getCategoryId());
        Apartment apartment = apartmentRepository.getById(req.getApartmentId());
        if (ObjectUtil.isEmpty(apartment)) {
            throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(), "门店不存在");
        }

        RoomEquipment roomEquipment = RoomEquipmentConvert.INSTANCE.convert3(req);
        roomEquipment.setDeptId(apartment.getDeptId());
        //如果是库房，只有位置类型
        if (roomEquipment.getPositionType().equals(EquipmentPositionType.STORE_ROOM.getCode() + "")) {
            roomEquipment.setArea(null);
            roomEquipment.setBuildingNo(null);
            roomEquipment.setUnitNo(null);
            roomEquipment.setFloorNo(null);
            roomEquipment.setIsConcentrated(null);
            roomEquipment.setIsPub(null);
            roomEquipment.setRoomId(null);
            //库房默认闲置状态
            roomEquipment.setStatus(String.valueOf(EquipmentStatus.LEAVE_UNUSED.getCode()));
        }
        if (roomEquipment.getPositionType().equals(EquipmentPositionType.PUB_PlACE.getCode() + "")) {
            roomEquipment.setIsPub(true);
            roomEquipment.setRoomId(null);
            roomEquipment.setFloorNo(null);
            roomEquipment.setStatus(String.valueOf(EquipmentStatus.INUSE.getCode()));
        }
        if (roomEquipment.getPositionType().equals(EquipmentPositionType.ROOM_HOUSE.getCode() + "")) {
            roomEquipment.setIsPub(false);
            //新增的 如果房源状态是入住中为在用， 获取房态
            roomEquipment.setStatus(String.valueOf(EquipmentStatus.INUSE.getCode()));
        }
        //设置资产编码
        roomEquipment.setAssetCode(codeUtil.nextCode("ZC"));
        roomEquipmentRepository.save(roomEquipment);
        return roomEquipment.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean edit(RoomEquipmentUpdateReqVO req) {
        Assert.isFalse(req.getId() == null, "编辑资产请传入id！");
        // 编辑 若传入则校验
        //校验图片，最大不能超过五张，批量上传不能上传所以不校验此项
        if (StrUtil.isNotBlank(req.getPic())) {
            validatePic(req.getPic());
        }
        // 校验资产类别
        if (req.getCategoryId() != null) {
            validateCategoryId(req.getCategoryId());
        }
        RoomEquipment roomEquipment = new RoomEquipment();
        BeanUtils.copyProperties(req, roomEquipment);
        //数据转换
        //如果是库房，只有位置类型
        if (roomEquipment.getPositionType().equals(EquipmentPositionType.STORE_ROOM.getCode() + "")) {
            roomEquipment.setArea(null);
            roomEquipment.setBuildingNo(null);
            roomEquipment.setUnitNo(null);
            roomEquipment.setFloorNo(null);
            roomEquipment.setIsConcentrated(null);
            roomEquipment.setRoomId(null);
            roomEquipment.setIsPub(null);
            //新增的 默认状态为 “未用”
            roomEquipment.setStatus(String.valueOf(EquipmentStatus.LEAVE_UNUSED.getCode()));
        }
        if (roomEquipment.getPositionType().equals(EquipmentPositionType.PUB_PlACE.getCode() + "")) {
            roomEquipment.setIsPub(true);
            roomEquipment.setRoomId(null);
            roomEquipment.setFloorNo(null);
            if (req.getIsConcentrated()) {
                roomEquipment.setUnitNo(null);
            }
            roomEquipment.setStatus(String.valueOf(EquipmentStatus.INUSE.getCode()));
        }
        if (roomEquipment.getPositionType().equals(EquipmentPositionType.ROOM_HOUSE.getCode() + "")) {
            roomEquipment.setIsPub(false);
            //新增的 默认状态为 “在用”
            roomEquipment.setStatus(String.valueOf(EquipmentStatus.INUSE.getCode()));
        }

        return roomEquipmentRepository.updateById(roomEquipment);
    }

    //字段处理
    RoomEquipment convertToRoomEquipment2(RoomEquipmentImport rmreq) {
        RoomEquipment roomEquipment = new RoomEquipment();

        int positionType = EquipmentPositionType.ROOM_HOUSE.getCode();
        //所属房间
        Integer roomId = rmreq.getRoomId();
        if (roomId == null) {
            positionType = EquipmentPositionType.STORE_ROOM.getCode();
        }
        RoomHouse room = roomHouseRepository.getById(roomId);
        //房间状态为在租状态时，资产状态默认为在用，否则为未用
        String status = EquipmentStatus.INUSE.getCode();

        StringBuilder code = new StringBuilder();

        EquipmentCategory equipmentCategory = equipmentCategoryRepository.getById(rmreq.getCategoryId());

        //生成资产编码
        while (true) {
            String randomCode = RandomUtil.randomString(5);
            code = new StringBuilder(String.format("ZC%06d%s%s", SecurityFrameworkUtils.getLoginUserId(), equipmentCategory.getCode(), randomCode));
            Long count = roomEquipmentRepository.countByCode(code.toString());
            if (count > 0) {
                continue;
            }
            break;
        }

        roomEquipment = RoomEquipmentConvert.INSTANCE.convert(rmreq);
        roomEquipment.setPositionType(String.valueOf(positionType));
        roomEquipment.setStatus(String.valueOf(status));
        roomEquipment.setCode(code.toString());

        return roomEquipment;
    }

    @Override
    public void updateStatus(Long id, String status) {
        //4是报废 5是遗失
        RoomEquipment roomEquipment = new RoomEquipment();
        //校验
        RoomEquipment byId = roomEquipmentRepository.getById(id);
        Assert.isFalse(ObjectUtil.isEmpty(byId), "该资产不存在！");
        Assert.isFalse(byId.getStatus().equals(String.valueOf(EquipmentStatus.LOSE.getCode())), "遗失状态不可操作！");
        //更新实体类赋值
        byId.setStatus(status);
        roomEquipmentRepository.updateById(byId);
    }

    @Override
    public void updateBatchDp(RoomEquipmentUpDpReqVo req) {
        log.info("批量调配...");
        //更新实体类赋值
        List<RoomEquipment> list = new ArrayList<>();
        Apartment apartment = apartmentRepository.getById(req.getApartmentId());
        if (ObjectUtil.isEmpty(apartment)) {
            throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(), "门店不存在");
        }
        for (Long id : req.getIds()) {
            RoomEquipment roomEquipment = new RoomEquipment();
            roomEquipment.setId(id);
            roomEquipment.setDeptId(apartment.getDeptId());
            roomEquipment.setPositionType(req.getPositionType());
            if (req.getPositionType().equals(EquipmentPositionType.ROOM_HOUSE.getCode() + "")) {
                roomEquipment.setIsPub(false);
                //新增的 默认状态为 “在用”
                roomEquipment.setStatus(String.valueOf(EquipmentStatus.INUSE.getCode()));
                roomEquipment.setRoomId(req.getRoomId());
                roomEquipment.setApartmentId(req.getApartmentId());
                roomEquipment.setArea(req.getArea());
                roomEquipment.setUnit(req.getUnitNo());
                roomEquipment.setBuildingNo(req.getBuildingNo());
                roomEquipment.setFloorNo(req.getFloorNo());
                roomEquipment.setUnitNo(req.getUnitNo());
                roomEquipment.setIsConcentrated(req.getIsConcentrated());
            } else if (req.getPositionType().equals(EquipmentPositionType.STORE_ROOM.getCode() + "")) {
                roomEquipment.setArea(null);
                roomEquipment.setBuildingNo(null);
                roomEquipment.setUnitNo(null);
                roomEquipment.setFloorNo(null);
                roomEquipment.setIsConcentrated(null);
                roomEquipment.setIsPub(null);
                roomEquipment.setApartmentId(req.getApartmentId());
                //新增的 默认状态闲置
                roomEquipment.setStatus(String.valueOf(EquipmentStatus.LEAVE_UNUSED.getCode()));
            } else if (req.getPositionType().equals(EquipmentPositionType.PUB_PlACE.getCode() + "")) {
                roomEquipment.setIsPub(true);
                roomEquipment.setRoomId(null);
                roomEquipment.setFloorNo(null);
                if (req.getIsConcentrated()) {
                    roomEquipment.setUnitNo(null);
                } else {
                    roomEquipment.setUnit(req.getUnitNo());
                }
                roomEquipment.setApartmentId(req.getApartmentId());
                roomEquipment.setArea(req.getArea());
                roomEquipment.setBuildingNo(req.getBuildingNo());
                roomEquipment.setIsConcentrated(req.getIsConcentrated());
                roomEquipment.setStatus(String.valueOf(EquipmentStatus.INUSE.getCode()));
            }

            list.add(roomEquipment);
        }

        roomEquipmentRepository.updateBatchById(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class) // 添加事务，异常则回滚所有导入
    public RoomEquipmentRespVO importRoomEquipment(List<RoomEquipmentImport> list) {
        if (CollUtil.isEmpty(list)) {
            throw new IllegalArgumentException("导入房间资产不能为空！");
        }
        RoomEquipmentRespVO respVO = RoomEquipmentRespVO.builder().createRoomEquipment(new ArrayList<>())
                .updateRoomEquipment(new ArrayList<>()).failureRoomEquipment(new LinkedHashMap<>()).build();

        List<RoomEquipment> equipmentList = new ArrayList<>();
        for (RoomEquipmentImport importVO : list) {
            // 校验，判断是否有不符合的原因
            try {
                // 校验资产类别是否存在
                validateCategoryId(importVO.getCategoryId());
            } catch (ServiceException ex) {
                respVO.getFailureRoomEquipment().put(importVO.getName(), ex.getMessage());
                return respVO;
            }
            //数据转换
            equipmentList.add(convertToRoomEquipment2(importVO));
        }

        roomEquipmentRepository.saveBatch(equipmentList);

        return respVO;
    }

    @Override
    public IPage<RoomEquipmentPageResp> pageRoomEquipmentByRoomId(RoomEquipmentPageReqVO reqVO) {
        return roomEquipmentRepository.pageRoomEquipmentByRoomId(reqVO);

    }

    @Override
    public List<RoomEquipmentExportRespVo> exportRoomEquipment(RoomEquipmentExportReq roomEquipmentExportReq) {
        LambdaQueryWrapper<RoomEquipment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RoomEquipment::getRoomId, roomEquipmentExportReq.getRoomId());

        List<RoomEquipment> list = roomEquipmentRepository.exportRoomEquipment(wrapper);

        return RoomEquipmentConvert.INSTANCE.convertList(list);
    }

    @Override
    public RoomEquipmentQueryResp queryRoomEquipmentById(Integer id) {
        RoomEquipmentQueryResp resp = roomEquipmentRepository.queryRoomEquipmentById(id);
        resp.setWarrantyTimeStr(LocalDateTimeUtil.format(resp.getWarrantyTime(), "yyyy-MM-dd"));
        resp.setPurchaseTimeStr(LocalDateTimeUtil.format(resp.getPurchaseTime(), "yyyy-MM-dd"));
        return resp;
    }

    @Override
    public void deleteById(Long id) {
        this.baseMapper.deleteById(id);
    }

    @Override
    public CommonResult<List<RoomEquipmentVO>> getRoomEquipmentByRoomId(Long roomId) {
        List<RoomEquipmentQueryResp> list = roomEquipmentRepository.getByRoomId(roomId);
        List<RoomEquipmentVO> collect = list.stream().map(e -> {
            RoomEquipmentVO vo = new RoomEquipmentVO();
            BeanUtils.copyProperties(e, vo);
            if (StringUtils.isNotEmpty(e.getPositionType())) {
                vo.setPositionTypeName(EquipmentPositionType.getNameByCode(e.getPositionType()));
            }
            if (StringUtils.isNotEmpty(e.getOwn())) {
                vo.setOwnName(EquipmentOwn.getNameByCode(e.getOwn()));
            }
            if (StringUtils.isNotEmpty(e.getPosition())) {
                vo.setRoomPositionName(EquipmentPositionType.getNameByCode(e.getPosition()));
            }
            if (StringUtils.isNotEmpty(e.getStatus())) {
                vo.setStatus(EquipmentStatus.getNameByCode(e.getStatus()));
            }
            return vo;
        }).collect(Collectors.toList());
        return CommonResult.success(collect);
    }

    @Override
    public Boolean unbindingEquipment(Long roomId) {
        return roomEquipmentRepository.unbindingEquipment(roomId);
    }

    @Override
    public void batchImportEquipment(List<PartLeaseEquipmentTemplateVo> equipments, Long apartmentId, Long tenantId, Long userId, String flag) {
        // 校验公寓信息
        Apartment apartment = apartmentRepository.getById(apartmentId);
        Assert.isTrue(ObjectUtil.isNotEmpty(apartment), "公寓信息不存在");
        //批量校验资产类别
        batchValidEquipment(equipments, flag);
        //校验房间存不存在
        batchValidRoom(equipments, apartment, flag);
        //批量保存到
        batchSaveEquipments(equipments, apartment, userId);

    }

    @Override
    public Boolean equipmentImport(EquipmentImportReq req, String key) {
        TransactionStatus transactionStatus = transactionManager.getTransaction(transactionDefinition);
//        try (ExcelReader excelReader = EasyExcel.read("G:\\资产导入模板.xlsx").build()) {
        try (ExcelReader excelReader = EasyExcel.read(oosFileService.oosDownloadFile(req.getFileUrl())).build()) {
            ReadSheet readSheet1 =
                    EasyExcel.readSheet(0).head(WholeLeaseEquipmentTemplateVo.class).registerReadListener(new WholeLeaseEquipmentListener(req.getApartmentId(), req.getTenantId(), req.getUserId(), new AtomicInteger(), this)).build();
            ReadSheet readSheet2 =
                    EasyExcel.readSheet(1).head(PartLeaseEquipmentTemplateVo.class).registerReadListener(new PartLeaseEquipmentListener(req.getApartmentId(), req.getTenantId(), req.getUserId(), new AtomicInteger(), this)).build();
            excelReader.read(readSheet1, readSheet2);
            transactionManager.commit(transactionStatus);
            EquipmentImportResult equipmentImportResult = new EquipmentImportResult(2, "导入完成");
            stringRedisTemplate.opsForValue().set(key, JsonUtils.toJsonString(equipmentImportResult), 1, TimeUnit.HOURS);
        } catch (Exception e) {
            EquipmentImportResult equipmentImportResult = new EquipmentImportResult(3, "导入失败:" + e.getMessage());
            stringRedisTemplate.opsForValue().set(key, JsonUtils.toJsonString(equipmentImportResult), 1, TimeUnit.HOURS);
            transactionManager.rollback(transactionStatus);
            throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(), e.getMessage());
        }
        return true;
    }

    private void batchSaveEquipments(List<PartLeaseEquipmentTemplateVo> equipments, Apartment apartment, Long userId) {
        List<RoomEquipment> roomEquipments = new ArrayList<>();
        for (PartLeaseEquipmentTemplateVo e : equipments) {
            RoomEquipment roomEquipment = new RoomEquipment();
            roomEquipment.setRoomId(e.getRoomId());
            roomEquipment.setName(e.getName());
            roomEquipment.setUnit(e.getUnit());
            roomEquipment.setFloorNo(e.getFloorNo());
            roomEquipment.setArea(e.getArea());
            roomEquipment.setApartmentId(apartment.getId());
            roomEquipment.setBuildingNo(e.getBuildingNo());
            roomEquipment.setCategoryId(e.getCategoryId());
            //如果供应商不为空
            if (StringUtils.isNotEmpty(e.getSupplier())) {
                try {
                    List<EquipmentSupplier> list = supplierRepository.list(
                            new LambdaQueryWrapper<EquipmentSupplier>()
                                    .eq(EquipmentSupplier::getName, e.getSupplier())
                    );
                    if (list != null && list.size() == 1) {
                        roomEquipment.setSupplierId(list.get(0).getId());
                    }
                } catch (Exception ex) {
                    log.info("查找供应商id出现异!");
                }

            }
            //所属方
            if (StringUtils.isNotEmpty(e.getOwn())) {
                roomEquipment.setOwn(EquipmentOwn.getCodeByName(e.getOwn()) + "");
            }
            roomEquipment.setManagerId(userId);
            //负责人
            try {
                CommonResult<AdminUserRespDTO> userData = adminUserApi.getUser(userId);
                if (userData.isSuccess()) {
                    AdminUserRespDTO user = userData.getData();
                    if (ObjectUtil.isNotEmpty(user)) {
                        roomEquipment.setManager(user.getNickname());
                    }
                }
            } catch (Exception ex) {
                log.info("根据用户id查询到负责人!");
            }

//            if (e.getPositionTypeName().equals(EquipmentPositionType.STORE_ROOM.getName())) {
//                roomEquipment.setPositionType(EquipmentPositionType.STORE_ROOM.getCode() + "");
//                roomEquipment.setArea(null);
//                roomEquipment.setBuildingNo(null);
//                roomEquipment.setUnitNo(null);
//                roomEquipment.setFloorNo(null);
//                roomEquipment.setIsConcentrated(null);
//                roomEquipment.setIsPub(null);
//                roomEquipment.setRoomId(null);
//                //库房默认闲置状态
//                roomEquipment.setStatus(String.valueOf(EquipmentStatus.LEAVE_UNUSED.getCode()));
//            }
//            if (e.getPositionTypeName().equals(EquipmentPositionType.PUB_PlACE.getName())) {
//                roomEquipment.setPositionType(EquipmentPositionType.PUB_PlACE.getCode() + "");
//                roomEquipment.setIsPub(true);
//                roomEquipment.setRoomId(null);
//                roomEquipment.setFloorNo(null);
//                roomEquipment.setStatus(String.valueOf(EquipmentStatus.INUSE.getCode()));
//            }
            if (e.getPositionTypeName().equals(EquipmentPositionType.ROOM_HOUSE.getName())) {
                roomEquipment.setPositionType(EquipmentPositionType.ROOM_HOUSE.getCode() + "");
                roomEquipment.setIsPub(false);
                //新增的 如果房源状态是入住中为在用， 获取房态
                roomEquipment.setStatus(String.valueOf(EquipmentStatus.INUSE.getCode()));
            }
            //设置资产编码
            roomEquipment.setAssetCode(codeUtil.nextCode("ZC"));
            roomEquipment.setDeptId(apartment.getDeptId());
            roomEquipments.add(roomEquipment);
        }
        if (roomEquipments != null && roomEquipments.size() > 0) {
            roomEquipmentRepository.saveBatch(roomEquipments);
        }
    }

    private List<PartLeaseEquipmentTemplateVo> batchValidRoom(List<PartLeaseEquipmentTemplateVo> equipments, Apartment apartment, String flag) {
        if (flag.equals("whole")) {
            for (int i = 0; i < equipments.size(); i++) {
                PartLeaseEquipmentTemplateVo e = equipments.get(i);
                List<RoomHouse> list = roomHouseRepository.list(
                        new LambdaQueryWrapper<RoomHouse>()
                                .eq(RoomHouse::getApartmentId, apartment.getId())
                                .eq(RoomHouse::getIsConcentrated, true)
                                .eq(RoomHouse::getArea, e.getArea())
                                .eq(RoomHouse::getBuildingNo, e.getBuildingNo())
                                .eq(RoomHouse::getFloorNo, e.getFloorNo())
                                .eq(RoomHouse::getName, e.getRoom())
                );
                if (CollectionUtils.isEmpty(list)) {
                    throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(), "集中式房间第" + (i + 1) + "行不存在");
                } else {
                    if (list.size() > 1) {
                        throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(), "集中式房间第" + (i + 1) + "行存在多个相同房间号");
                    } else {
                        //如果
                        RoomHouse roomHouse = list.get(0);
                        if (e.getPositionTypeName().equals(EquipmentPositionType.ROOM_HOUSE.getName())) {
                            //如果不是整租
                            if ((!roomHouse.getIsWhole() && ObjectUtil.isEmpty(roomHouse.getSuperId())) || (!roomHouse.getIsWhole() && roomHouse.getRoomType().equals(RoomTypeEnum.GGQY.getValue()))) {
                                throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(), "集中式房间第" + (i + 1) + "行导入的房源房间号有误");
                            }
                        }
                        e.setRoomId(roomHouse.getId());
                    }
                }
            }
        } else {
            for (int i = 0; i < equipments.size(); i++) {
                PartLeaseEquipmentTemplateVo e = equipments.get(i);
                List<RoomHouse> list = roomHouseRepository.list(
                        new LambdaQueryWrapper<RoomHouse>()
                                .eq(RoomHouse::getApartmentId, apartment.getId())
                                .eq(RoomHouse::getIsConcentrated, false)
                                .eq(RoomHouse::getArea, e.getArea())
                                .eq(RoomHouse::getBuildingNo, e.getBuildingNo())
                                .eq(RoomHouse::getUnitNo, e.getUnitNo())
                                .eq(RoomHouse::getFloorNo, e.getFloorNo())
                                .eq(RoomHouse::getName, e.getRoom())
                );
                if (CollectionUtils.isEmpty(list)) {
                    throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(), "分散式房间第" + (i + 1) + "行不存在");
                } else {
                    if (list.size() > 1) {
                        throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(), "分散式房间第" + (i + 1) + "行存在多个相同房间号");
                    } else {
                        //如果
                        RoomHouse roomHouse = list.get(0);
                        if (e.getPositionTypeName().equals(EquipmentPositionType.ROOM_HOUSE.getName())) {
                            //如果不是整租
                            if ((!roomHouse.getIsWhole() && ObjectUtil.isEmpty(roomHouse.getSuperId())) || (!roomHouse.getIsWhole() && roomHouse.getRoomType().equals(RoomTypeEnum.GGQY.getValue()))) {
                                throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(), "集中式房间第" + (i + 1) + "行导入的房源房间号有误");
                            }
                        }
                        e.setRoomId(roomHouse.getId());
                    }
                }
            }
        }
        return equipments;
    }

    private List<PartLeaseEquipmentTemplateVo> batchValidEquipment(List<PartLeaseEquipmentTemplateVo> equipments, String flag) {

        for (int i = 0; i < equipments.size(); i++) {
            PartLeaseEquipmentTemplateVo e = equipments.get(i);
            List<EquipmentCategory> list = equipmentCategoryRepository.list(
                    new LambdaQueryWrapper<EquipmentCategory>()
                            .eq(EquipmentCategory::getName, e.getCategoryName())
            );
            if (CollectionUtils.isEmpty(list)) {
                if (flag.equals("whole")) {
                    throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(), "集中式资产类型第" + (i + 1) + "行不存在");
                } else {
                    throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(), "分散式资产类型第" + (i + 1) + "行不存在");
                }
            } else {
                if (list.size() > 1) {
                    if (flag.equals("whole")) {
                        throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(), "集中式资产类型第" + (i + 1) + "行存在多个相同资产类别");
                    } else {
                        throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(), "分散式资产类型第" + (i + 1) + "行存在多个相同资产类别");
                    }
                } else {
                    e.setCategoryId(list.get(0).getId());
                }
            }
        }
        return equipments;
    }

    @VisibleForTesting
    void validatePic(String picList) {
        if (picList != null && picList.split(",").length > 5) {
            throw new IllegalArgumentException("图片数量最大不能超过五张");
        }
    }

    @VisibleForTesting
    void validateCategoryId(Long categoryId) {
        if (categoryId == null) {
            throw new IllegalArgumentException("资产类别未选取！");
        }
        EquipmentCategory equipmentCategory = equipmentCategoryRepository.getById(categoryId);

        if (equipmentCategory == null) {
            throw new IllegalArgumentException("资产类别不存在:" + categoryId);
        }
    }

    @VisibleForTesting
    void validateSupplierId(Long supplierId) {
        if (supplierId == null) {
            throw new IllegalArgumentException("供应商未选取！");
        }
        EquipmentSupplier equipmentSupplier = equipmentSupplierRepository.getById(supplierId);
        if (equipmentSupplier == null) {
            throw new IllegalArgumentException("供应商不存在:" + supplierId);
        }
    }


}
